import store from "@/store/index.js"
class websocket {
	constructor(url, onReceive) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		//心跳监测
		this.timeout = 10000 //多少秒执行检测
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.onReceive = onReceive
		this.socketTask = null
	}
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			header: {
				token: uni.getStorageSync("token")
			},
			success() {
				return this.socketTask
			},
			fail() {
				this.reconnect()
			}
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			store.state.loading = false
			uni.$emit("unloading")
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start(); //开启心跳
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				// console.log(res.data)
				this.onReceive(res.data)
			});
		})
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onError(() => {
			// console.log("已经被关闭了")
			store.state.loading = true
			uni.$emit("loading")
			console.log("ws error")
			if (this.is_open_socket === true)
				this.reconnect();
		})
	}
	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		uni.sendSocketMessage({
			// this.socketTask.send({
			data: JSON.stringify(value),
			success() {
				console.log("消息发送成功");
			},
			// fail() {
			// 	this.reconnect();
			// }
		});
	}
	start() {
		this.heartbeatInterval = setInterval(() => {
			let data = {
				fromId: store.state.userInfo.id,
				toId: store.state.userInfo.id,
				messageType: -1,
				data: "heart beat"
			}
			console.log("heart")
			this.send(data);
		}, this.timeout)
	}
	reconnect() {
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (this.is_open_socket) {
			console.log("重连ws")
			this.reconnectTimeOut = setTimeout(() => {
				store.state.friendRequestNum = 0;
				store.state.groupRequestNum = 0;
				this.connectSocketInit();
			}, 1000)
		}
	}
	close() {
		clearInterval(this.heartbeatInterval)
		uni.closeSocket({
			success() {
				this.is_open_socket = false
				console.log("WebSocket关闭成功")
			}
		})
	}
}
module.exports = websocket
